class ChatbotSDK {
  constructor(config) {
    this.iframe = null;
    this.container = null;
    this.chatIcon = null;
    this.isVisible = false;
    this.isDragging = false;
    this.isResizing = false;
    this.dragOffset = { x: 0, y: 0 };
    this.config = {
      width: '350px',
      height: '600px',
      position: 'fixed',
      bottom: '20px',
      right: '20px',
      url: 'http://47.236.204.213:3002',
      iconSize: '56px',
      minWidth: '300px',
      minHeight: '400px',
      maxWidth: '800px',
      maxHeight: '800px',
      ...config,
    };
  }

  init() {
    this.container = document.getElementById(this.config.containerId);
    if (!this.container) {
      throw new Error(`Container with id ${this.config.containerId} not found`);
    }

    // Create chat icon wrapper for pulse effect
    const iconWrapper = document.createElement('div');
    iconWrapper.style.position = 'fixed';
    iconWrapper.style.bottom = '20px';
    iconWrapper.style.right = '20px';
    iconWrapper.style.zIndex = '9999';

    // Create pulse effect element
    const pulse = document.createElement('div');
    pulse.style.position = 'absolute';
    pulse.style.width = '100%';
    pulse.style.height = '100%';
    pulse.style.borderRadius = '50%';
    pulse.style.backgroundColor = 'rgba(51, 51, 51, 0.2)';
    pulse.style.animation = 'pulse 2s infinite';

    // Add keyframes
    const style = document.createElement('style');
    style.textContent = `
      @keyframes pulse {
        0% { transform: scale(1); opacity: 0.5; }
        70% { transform: scale(1.3); opacity: 0; }
        100% { transform: scale(1.3); opacity: 0; }
      }
      @keyframes fadeIn {
        0% { opacity: 0; transform: translateY(10px); }
        100% { opacity: 1; transform: translateY(0); }
      }
      @keyframes slideIn {
        0% { transform: translateY(20px); opacity: 0; }
        100% { transform: translateY(0); opacity: 1; }
      }
      @keyframes rotateIn {
        0% { transform: rotate(-180deg) scale(0.3); }
        100% { transform: rotate(0) scale(1); }
      }
      .resize-handle {
        position: absolute;
        z-index: 9999;
        opacity: 0;
        transition: all 0.3s ease;
      }
      .chat-window-visible .resize-handle {
        opacity: 1;
      }
      .resize-handle.right {
        right: -4px;
        top: 30px;
        width: 8px;
        height: calc(100% - 30px);
        cursor: e-resize;
      }
      .resize-handle.right:after {
        content: '';
        position: absolute;
        right: 3px;
        top: 0;
        height: 100%;
        width: 2px;
        background: transparent;
        transition: background 0.2s;
      }
      .resize-handle.right:hover:after {
        background: rgba(0, 0, 0, 0.2);
      }
      .resize-handle.bottom {
        bottom: -4px;
        left: 0;
        height: 8px;
        width: 100%;
        cursor: s-resize;
      }
      .resize-handle.bottom:after {
        content: '';
        position: absolute;
        bottom: 3px;
        left: 0;
        width: 100%;
        height: 2px;
        background: transparent;
        transition: background 0.2s;
      }
      .resize-handle.bottom:hover:after {
        background: rgba(0, 0, 0, 0.2);
      }
      .resize-handle.corner {
        right: -4px;
        bottom: -4px;
        width: 12px;
        height: 12px;
        cursor: se-resize;
      }
      .resize-handle.corner:after {
        content: '';
        position: absolute;
        right: 3px;
        bottom: 3px;
        width: 6px;
        height: 6px;
        border-right: 2px solid transparent;
        border-bottom: 2px solid transparent;
        transition: border-color 0.2s;
      }
      .resize-handle.corner:hover:after {
        border-color: rgba(0, 0, 0, 0.2);
      }
      .chat-header {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 30px;
        background: #333;
        border-top-left-radius: 16px;
        border-top-right-radius: 16px;
        cursor: move;
        display: flex;
        align-items: center;
        padding: 0 15px;
        color: white;
        font-family: system-ui, -apple-system, sans-serif;
        font-size: 14px;
        user-select: none;
        opacity: 0;
        transform: translateY(-10px);
        transition: all 0.3s ease;
      }
      .chat-window-visible .chat-header {
        opacity: 1;
        transform: translateY(0);
      }
      .chat-header:hover {
        background: #444;
      }
      .chat-content {
        position: relative;
        width: 100%;
        height: 100%;
        border-radius: 16px;
        overflow: hidden;
        opacity: 0;
        transform: translateY(10px);
        transition: all 0.3s ease;
      }
      .chat-window-visible .chat-content {
        background: white;
        opacity: 1;
        transform: translateY(0);
      }
      .chat-container {
        background: transparent;
        border-radius: 16px;
        transform: translate3d(0,0,0);
        will-change: transform;
        transition: all 0.3s ease;
        z-index: 1;
      }
      .chat-window-visible .chat-container {
        background: white;
        box-shadow: 0 8px 24px rgba(0,0,0,0.1);
      }
    `;
    document.head.appendChild(style);

    // Create chat icon
    this.chatIcon = document.createElement('div');
    this.chatIcon.style.width = this.config.iconSize;
    this.chatIcon.style.height = this.config.iconSize;
    this.chatIcon.style.borderRadius = '50%';
    this.chatIcon.style.backgroundColor = '#333333';
    this.chatIcon.style.cursor = 'pointer';
    this.chatIcon.style.position = 'relative';
    this.chatIcon.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
    this.chatIcon.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
    this.chatIcon.style.display = 'flex';
    this.chatIcon.style.alignItems = 'center';
    this.chatIcon.style.justifyContent = 'center';
    this.chatIcon.style.animation =
      'rotateIn 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
    this.chatIcon.innerHTML = `
      <svg width="50%" height="50%" viewBox="0 0 24 24" fill="white" style="transition: all 0.3s ease">
        <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
      </svg>
    `;

    // Add hover effect
    this.chatIcon.onmouseover = () => {
      this.chatIcon.style.backgroundColor = '#000000';
      this.chatIcon.style.transform = 'scale(1.1) translateY(-2px)';
      this.chatIcon.style.boxShadow = '0 6px 16px rgba(0,0,0,0.2)';
    };
    this.chatIcon.onmouseout = () => {
      this.chatIcon.style.backgroundColor = '#333333';
      this.chatIcon.style.transform = 'scale(1) translateY(0)';
      this.chatIcon.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
    };

    // Add click handler
    this.chatIcon.onclick = () => {
      if (this.isVisible) {
        this.hide();
      } else {
        this.show();
      }
    };

    // Create chat wrapper
    const chatWrapper = document.createElement('div');
    chatWrapper.className = 'chat-content';

    // Create chat header for dragging
    const header = document.createElement('div');
    header.className = 'chat-header';
    header.textContent = 'Chat';

    // Create iframe
    this.iframe = document.createElement('iframe');
    this.iframe.src = this.config.url;
    this.iframe.style.width = '100%';
    this.iframe.style.height = 'calc(100% - 30px)';
    this.iframe.style.border = 'none';
    this.iframe.style.marginTop = '30px';
    this.iframe.style.display = 'none';
    this.iframe.style.transition = 'all 0.3s ease';

    // Create resize handles
    const rightHandle = document.createElement('div');
    rightHandle.className = 'resize-handle right';
    const bottomHandle = document.createElement('div');
    bottomHandle.className = 'resize-handle bottom';
    const cornerHandle = document.createElement('div');
    cornerHandle.className = 'resize-handle corner';

    if (this.config.position === 'fixed') {
      this.container.style.position = 'fixed';
      this.container.style.bottom = '90px';
      this.container.style.right = this.config.right;
    }

    this.container.style.width = this.config.width;
    this.container.style.height = this.config.height;
    this.container.className = 'chat-container';

    // Add drag functionality with performance optimization
    this.initDragging(header);

    // Add resize functionality
    this.initResizing(rightHandle, 'right');
    this.initResizing(bottomHandle, 'bottom');
    this.initResizing(cornerHandle, 'corner');

    // Append elements
    chatWrapper.appendChild(header);
    chatWrapper.appendChild(this.iframe);
    this.container.appendChild(chatWrapper);
    this.container.appendChild(rightHandle);
    this.container.appendChild(bottomHandle);
    this.container.appendChild(cornerHandle);

    iconWrapper.appendChild(pulse);
    iconWrapper.appendChild(this.chatIcon);
    document.body.appendChild(iconWrapper);
  }

  show() {
    if (this.iframe) {
      this.iframe.style.display = 'block';
      requestAnimationFrame(() => {
        this.isVisible = true;
        this.container.classList.add('chat-window-visible');
        this.container.style.zIndex = '9998';
        this.chatIcon.innerHTML = `
          <svg width="50%" height="50%" viewBox="0 0 24 24" fill="white" style="transition: all 0.3s ease; transform: rotate(180deg);">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        `;
      });
    }
  }

  hide() {
    if (this.iframe) {
      this.isVisible = false;
      this.container.classList.remove('chat-window-visible');
      this.container.style.zIndex = '1';
      this.chatIcon.innerHTML = `
        <svg width="50%" height="50%" viewBox="0 0 24 24" fill="white" style="transition: all 0.3s ease">
          <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
        </svg>
      `;
      setTimeout(() => {
        if (!this.isVisible) {
          this.iframe.style.display = 'none';
        }
      }, 300);
    }
  }

  destroy() {
    if (this.iframe && this.container) {
      this.container.removeChild(this.iframe);
      this.iframe = null;
    }
    if (this.chatIcon) {
      const iconWrapper = this.chatIcon.parentElement;
      if (iconWrapper) {
        document.body.removeChild(iconWrapper);
      }
      this.chatIcon = null;
    }
  }

  initDragging(header) {
    let rafId = null;
    let initialX, initialY;

    const onMouseMove = e => {
      if (!this.isDragging) return;

      if (rafId) {
        cancelAnimationFrame(rafId);
      }

      rafId = requestAnimationFrame(() => {
        const deltaX = e.clientX - initialX;
        const deltaY = e.clientY - initialY;

        const containerRect = this.container.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        // Calculate new position while keeping the container within viewport bounds
        let newX = Math.max(
          0,
          Math.min(
            viewportWidth - containerRect.width,
            containerRect.left + deltaX,
          ),
        );
        let newY = Math.max(
          0,
          Math.min(
            viewportHeight - containerRect.height,
            containerRect.top + deltaY,
          ),
        );

        this.container.style.left = newX + 'px';
        this.container.style.top = newY + 'px';

        initialX = e.clientX;
        initialY = e.clientY;
      });
    };

    const onMouseUp = () => {
      this.isDragging = false;
      if (rafId) {
        cancelAnimationFrame(rafId);
      }
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };

    header.onmousedown = e => {
      if (this.isResizing) return;

      this.isDragging = true;
      initialX = e.clientX;
      initialY = e.clientY;

      // Remove transition during drag
      this.container.style.transition = 'none';

      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    };
  }

  initResizing(handle, type) {
    let rafId = null;

    handle.onmousedown = e => {
      e.preventDefault();
      this.isResizing = true;
      const startX = e.clientX;
      const startY = e.clientY;
      const startWidth = parseInt(this.container.style.width);
      const startHeight = parseInt(this.container.style.height);

      const onMouseMove = e => {
        if (!this.isResizing) return;

        // Cancel any existing animation frame
        if (rafId) {
          cancelAnimationFrame(rafId);
        }

        // Schedule the update
        rafId = requestAnimationFrame(() => {
          if (type === 'right' || type === 'corner') {
            const width = startWidth + (e.clientX - startX);
            if (
              width >= parseInt(this.config.minWidth) &&
              width <= parseInt(this.config.maxWidth)
            ) {
              this.container.style.width = `${width}px`;
            }
          }

          if (type === 'bottom' || type === 'corner') {
            const height = startHeight + (e.clientY - startY);
            if (
              height >= parseInt(this.config.minHeight) &&
              height <= parseInt(this.config.maxHeight)
            ) {
              this.container.style.height = `${height}px`;
            }
          }
        });
      };

      const onMouseUp = () => {
        this.isResizing = false;
        if (rafId) {
          cancelAnimationFrame(rafId);
        }
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
      };

      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    };
  }
}

export { ChatbotSDK };
